package a.codetop;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class _16生成括号所有可能 {

    List<String> res = new ArrayList<>();
    StringBuilder tmp = new StringBuilder();

    public List<String> generateParenthesis(int n) {
        qian(n,n);
        return res;
    }

    //l:左括号剩余几个
    private void qian(int l, int r) {
        if(l==0 && r==0) {
            res.add(new String(tmp));
            return;
        }

        if(l>=1){
            tmp.append("("); qian(l-1,r); tmp.deleteCharAt(tmp.length()-1);
        }
        if(r>=1 && l<=r-1){ //注意是r-1之后和l比，和f(r-1)同的r-1
            tmp.append(")"); qian(l,r-1); tmp.deleteCharAt(tmp.length()-1);
        }
    }

    @Test
    public void test() {
        System.out.println(generateParenthesis(2));
    }
}
